package com.heartline.task;

import com.alibaba.fastjson.JSONObject;
import com.blade.ioc.annotation.Bean;
import com.blade.task.annotation.Schedule;
import com.hankcs.hanlp.HanLP;
import com.heartline.pojo.Calandar;
import com.heartline.util.DateUtils;
import com.heartline.util.StringUtils;
import com.soecode.wxtools.util.crypto.MD5;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;

import static io.github.biezhi.anima.Anima.select;

/**
 * 定时推送
 * Created by zhy on 2018/6/7.
 */
@Slf4j
@Bean
public class PushSchedule {

    /**
     * 定时拿calandar 默认4小时1次
     */
    @Schedule(name = "__calandar_task", cron = "0 0 0/4 * * ?")
    public void calandar_task() {
        log.debug("开始获取日历数据:");
        try {
            Response resp = Request.Get("http://appa.applinzi.com/api/test").connectTimeout(3000).execute();
            String str = resp.returnContent().asString();
            log.debug("接收到的数据:{}", str);
            JSONObject data = JSONObject.parseObject(str).getJSONObject("data");
            String content = data.getString("content").trim();
            String keyword = data.getString("keyword").trim();

            log.debug("calandar 解析的数据:{}", content);
            if (StringUtils.isBlank(content)) {
                log.debug("接口数据获取失败");
                return;
            }
            String md5 = MD5.getMD5(content, "UTF-8");
            String same = select().bySQL(String.class, "select date from t_calandar where md5 = ?", md5).one();
            if (StringUtils.isNotBlank(same)) {
                log.debug("获取数据存在重复,date:{}", same);
                return;
            }
//        HanLP.Config.enableDebug();
//            String keyWords = StringUtils.listToString(HanLP.extractKeyword(content, 5));
            String now = DateUtils.now();
            String newest = select().bySQL(String.class, "select date from t_calandar where date >= ? order by date desc", now).one();

            if (newest == null) {
                newest = now;
            } else {
                newest = DateUtils.formatDate(DateUtils.addDays(DateUtils.parseDate(newest), 1));
            }
            Calandar calandar = new Calandar(newest, keyword, content, md5);
            calandar.save();
            log.info("日历数据保存成功 {}", calandar);
        } catch (Exception e) {
            log.error("@小狐狸 你服务有问题！", e);
        }

    }
}
